package com.weme.chat

import android.app.ActivityOptions
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.OnKeyboardListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.weme.chat.adapter.ChatAdapter
import com.weme.chat.bean.GiftMessage
import com.weme.chat.bean.toMap
import com.weme.chat.databinding.ActivityChatBinding
import com.weme.chat.ext.addMessage
import com.weme.chat.ext.sendMseeage
import com.weme.chat.view.ChatInputListener
import com.weme.chat.viewmode.ChatViewMode
import com.weme.common.activity.LookBigImgActivity
import com.weme.common.activity.PhotoViewActivity
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterHelper.KEY_CONVERSATION_ID
import com.weme.common.arouter.ARouterHelper.KEY_COUNTRY
import com.weme.common.arouter.ARouterHelper.KEY_HEAD
import com.weme.common.arouter.ARouterHelper.KEY_NAME
import com.weme.common.arouter.ARouterHelper.KEY_USER
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.dialog.GiftDialog
import com.weme.common.dialog.GiftDialogCallback
import com.weme.common.dialog.GiftSendSuccessDialog
import com.weme.common.util.AgoraClient
import com.weme.common.util.DeviceId.getDeviceLanguage
import com.weme.common.util.GlideBlurTransformer
import com.weme.common.util.KeyboardVisibilityListener
import com.weme.common.util.KeyboardVisibilityListenerCallback
import com.weme.common.util.LiveConfig
import com.weme.common.util.UtilsApp
import com.weme.common.util.createProgressDialog
import com.weme.common.util.deviceSize
import com.weme.common.util.downloadMp4
import com.weme.common.util.fadeIn
import com.weme.common.util.getCountryBean
import com.weme.common.util.gone
import com.weme.common.util.isTypeImg
import com.weme.common.util.isVip
import com.weme.common.util.loadImage
import com.weme.common.util.loadVideoFromAssets
import com.weme.common.util.playSVGAFromAssets
import com.weme.common.util.scrollToBottom
import com.weme.common.util.setOnFastClickListener
import com.weme.common.util.setVerticalLayoutManager
import com.weme.common.util.setVisible
import com.weme.common.util.showToast
import com.weme.common.util.visible
import com.weme.common.view.BottomSelectionDialog
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.CustomDialogFragment
import com.weme.common.view.SelectionItem
import com.weme.common.view.SmoothImageView
import dev.kratos.api.im_server.v1.TranslateReply
import dev.kratos.api.user_server.v1.BlackReply
import dev.kratos.api.user_server.v1.BlackRequest
import dev.kratos.api.user_server.v1.GetAlbumReply
import dev.kratos.api.user_server.v1.GetAlbumRequest
import dev.kratos.api.user_server.v1.GetUserInfoRequest
import dev.kratos.api.user_server.v1.GiftInfo
import dev.kratos.api.user_server.v1.Media
import dev.kratos.api.user_server.v1.ReportReply
import dev.kratos.api.user_server.v1.ReportRequest
import dev.kratos.api.user_server.v1.SendGiftReply
import dev.kratos.api.user_server.v1.SendGiftRequest
import dev.kratos.api.user_server.v1.UnBlackReply
import dev.kratos.api.user_server.v1.Users
import io.agora.CallBack
import io.agora.MessageListener
import io.agora.ValueCallBack
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.CmdMessageBody
import io.agora.chat.Conversation
import io.agora.chat.CursorResult
import io.agora.chat.CustomMessageBody
import io.agora.chat.FetchMessageOption
import io.agora.chat.ImageMessageBody
import io.agora.chat.TextMessageBody
import io.agora.util.EMLog

enum class LoadDataType {
    LOCAL, ROAM,
}

@Route(path = ARouterPaths.CHAT_ACTIVITY)
class ChatActivity : BaseMvvmActivity<ActivityChatBinding, ChatViewMode>(), ChatInputListener,
    KeyboardVisibilityListenerCallback, BottomSelectionListener, GiftDialogCallback {
    override fun getViewModelClass(): Class<ChatViewMode> = ChatViewMode::class.java
    private val MAX_PAGESIZE = 40
    val type = Conversation.ConversationType.Chat
    lateinit var chatAdapter: ChatAdapter

    private var loadDataType = LoadDataType.LOCAL
    var user: Users? = null

    var countryFlag = ""

    lateinit var keyboardVisibilityListener: KeyboardVisibilityListener
    var alertDialog: AlertDialog? = null

    var lastMessageId = ""
    val items by lazy {
        mutableListOf<Media>()
    }


    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).keyboardEnable(true)
            .titleBar(mBinding.customTopNavigationBar)
            .setOnKeyboardListener(object : OnKeyboardListener {
                override fun onKeyboardChange(isPopup: Boolean, keyboardHeight: Int) {
                    mBinding.rcvList.scrollToBottom()
                }
            }).init()
        if (alertDialog == null) {
            alertDialog = createProgressDialog()
        }
        val receivedBundle = intent.extras //这里崩了还玩个锤子
        receivedBundle?.let {
            if (it.getSerializable(KEY_USER) == null) {
                chatAdapter = ChatAdapter(it.getString(KEY_HEAD).toString())
                viewModel.conversationId = it.getString(KEY_CONVERSATION_ID).toString()
                viewModel.userName = receivedBundle.getString(KEY_NAME).toString()
                mBinding.tvTitle.text = viewModel.userName
                viewModel.getChatUserInfo(
                    GetUserInfoRequest.newBuilder().addUids(viewModel.conversationId.toLong())
                        .build()
                )
                val country = getCountryBean(receivedBundle.getString(KEY_COUNTRY).toString())
                country?.let {
                    countryFlag = it.countryFlag
                    mBinding.imCountry.loadImage(it.countryFlag)
                }


            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    user = it.getSerializable(KEY_USER, Users::class.java)
                } else {
                    user = it.getSerializable(KEY_USER) as Users
                }
                user?.let {
                    chatAdapter = ChatAdapter(it.headPic)
                    viewModel.conversationId = it.uid.toString()
                    initInfo(it)
                }

            }
        }
        ChatClient.getInstance().chatManager().addMessageListener(msgListener)
        mBinding.ibBack.setOnClickListener { finish() }
        initAdapter()
        initOnclick()
        keyboardVisibilityListener = KeyboardVisibilityListener(this)
        keyboardVisibilityListener.addVisibilityListener(this)


        viewModel.getAlubm(
            GetAlbumRequest.newBuilder().setUid(viewModel.conversationId.toLong()).build()
        )
        LiveEventBus.get<Any>(LiveConfig.NET_WORK_CHAT).observe(this) {
            if (it is GetAlbumReply) {
                if (it.mediaList.isNotEmpty()) {
                    items.clear()
                    if (it.mediaList.isEmpty()) {
                        val media1 = Media.newBuilder().setType(1).setUrl("").build()
                        items.add(media1)
                    } else {
                        val sortedMediaList =
                            it.mediaList.sortedByDescending { !it.type.isTypeImg() }
                        items.addAll(sortedMediaList)
                    }
                    albumAdapter.addAll(items)
                }
                mBinding.scvAlbum.setVisible(items.isNotEmpty())
                mBinding.rcvList.scrollToBottom()

            } else if (it is Users) {//这个没用到
                user = it
                initInfo(it)
            } else if (it is SendGiftReply) {
                if (TextUtils.isEmpty(it.gift.giftUrl)) {
                    val giftSendSuccessDialog =
                        GiftSendSuccessDialog(user!!.nickname, user!!.headPic)
                    giftSendSuccessDialog.show(
                        this@ChatActivity.supportFragmentManager,
                        "GiftSendSuccessDialog"
                    )
                } else {
                    mBinding.playerView.loadVideoFromAssets(
                        it.gift.giftName + ".mp4",
                        it.gift.md5
                    ) {
                        downloadMp4(it.gift.giftUrl, it.gift.giftName) { isDow ->
                            if (isDow == true) {
                                mBinding.playerView.loadVideoFromAssets(
                                    it.gift.giftName + ".mp4",
                                    it.gift.md5
                                ) {

                                }
                            }

                        }
                    }
                }
                val customMessage = ChatMessage.createSendMessage(ChatMessage.Type.CUSTOM)
                val event = AgoraClient.EVENT_TYPING_GIFT
                val customBody = CustomMessageBody(event)
                val giftMessage = GiftMessage(it.gift.giftIcon, it.gift.giftUrl, it.gift.giftName)
                val giftMessageMap = giftMessage.toMap()
                customBody.params = giftMessageMap
                customMessage.addBody(customBody)
                customMessage.to = viewModel.conversationId
                customMessage.chatType = ChatMessage.ChatType.Chat
                customMessage.setMessageStatusCallback(object : CallBack {
                    override fun onSuccess() {

                    }

                    override fun onError(code: Int, error: String) {
                        Log.e("tag", error)
                    }
                })

                sendMseeage(customMessage)

            } else if (it is BlackReply) {
                ChatClient.getInstance().chatManager()
                    .deleteConversation(viewModel.conversationId, true)
                ChatClient.getInstance().chatManager().deleteConversationFromServer(
                    viewModel.conversationId,
                    type,
                    true,
                    object : CallBack {
                        override fun onSuccess() {

                        }

                        override fun onError(code: Int, error: String?) {

                        }

                    })
                user?.let {
                    showToast(
                        getString(
                            com.example.resources.R.string.block_bolck_tip,
                            it.nickname
                        )
                    )
                }
                UtilsApp.getActivityList().forEach {
                    if (it.get()!!.localClassName == "UserInfoActivity") {
                        it.get()!!.finish()
                    }
                }
                finish()
            } else if (it is UnBlackReply) { //  ChatClient.getInstance().contactManager().getBlackListUsernames()
            } else if (it is ReportReply) { //举报回调
                showToast(getString(com.example.resources.R.string.report_successful))
            } else if (it is TranslateReply) {
                com.weme.chat.ext.TranslationManager.getFirstItem()?.let { translationItem ->
                    val position = translationItem.position
                    val translatedContent = it.getContent(0)
                    Log.e("lang", chatAdapter.getItem(position)?.body!!.javaClass.toString())
                    (chatAdapter.getItem(position)?.body as? TextMessageBody)?.targetLanguages =
                        listOf(translatedContent)
                    chatAdapter.notifyItemChanged(position)
                    mBinding.rcvList.postDelayed({
                        mBinding.rcvList.scrollToBottom()
                    }, 200)

                    com.weme.chat.ext.TranslationManager.removeFirstItem()
                }
            }
        }

    }

    fun initInfo(it: Users) {
        viewModel.userName = it.nickname
        mBinding.tvTitle.text = viewModel.userName

        when (it.onlineStatus) {
            1 -> {
                getViewBinding().vCircle.visible()
                getViewBinding().tvOnline.visible()
                getViewBinding().vCircle.setBackgroundResource(com.example.resources.R.drawable.online_dot)
                getViewBinding().tvOnline.text = getString(com.example.resources.R.string.online)
            }

            2 -> {
                getViewBinding().vCircle.visible()
                getViewBinding().tvOnline.visible()
                getViewBinding().vCircle.setBackgroundResource(com.example.resources.R.drawable.busy_dot)
                getViewBinding().tvOnline.text = getString(com.example.resources.R.string.busy)
            }

            else -> {
                getViewBinding().vCircle.gone()
                getViewBinding().tvOnline.gone()
            }
        }
        val country = getCountryBean(it.countryCode)


        Log.e("country", "country_" + it.countryCode.toString())
        country?.let {
            countryFlag = it.countryFlag
            mBinding.imCountry.loadImage(it.countryFlag)
        }
    }


    fun initOnclick() {
        mBinding.tvTitle.setOnClickListener {
            mBinding.rcvList.scrollToBottom()
        }
        mBinding.ibMore.setOnClickListener {
            val selectionItems = listOf(
                SelectionItem(
                    getString(com.example.resources.R.string.report),
                    0,
                    object : BottomSelectionListener {
                        override fun onTitleClicked(position: Int) {
                            val reportList = listOf(
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_1),
                                    0,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_2),
                                    1,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_3),
                                    2,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_4),
                                    3,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_5),
                                    4,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_6),
                                    5,
                                    this@ChatActivity
                                ),
                                SelectionItem(
                                    getString(com.example.resources.R.string.report_7),
                                    6,
                                    this@ChatActivity
                                )
                            )
                            val reportDiaolg = BottomSelectionDialog.newInstance(reportList)
                            reportDiaolg.show(this@ChatActivity.supportFragmentManager, "")
                            reportDiaolg.setTitle(getString(com.example.resources.R.string.report))
                        }

                    }),
                SelectionItem(
                    getString(com.example.resources.R.string.block),
                    1,
                    object : BottomSelectionListener {
                        override fun onTitleClicked(position: Int) {
                            alertDialog?.show()
                            viewModel.setBlock(
                                BlackRequest.newBuilder()
                                    .setBlackUid(viewModel.conversationId.toLong()).build()
                            )


                        }

                    }),
            )


            val btndialog = BottomSelectionDialog.newInstance(selectionItems)
            btndialog.show(this.supportFragmentManager, "BottomSelectionDialog")
        }

        mBinding.imCall.setOnFastClickListener {
            val userBuilder = Users.newBuilder()
            user?.let { it1 ->
                userBuilder.uid = it1.uid
                userBuilder.nickname = it1.nickname
                userBuilder.age = it1.age
                userBuilder.setCountryCode(it1.countryCode)
            }

            userBuilder.addAllMedia(items)
            viewModel.callsPhone(userBuilder.build())
        }


    }

    override fun onPause() {
        super.onPause()
        mBinding.imCall.stopAnimation()
    }
   public override fun onResume() {
        super.onResume()
       mBinding.imCall.playSVGAFromAssets("video_button_male_call_message")
        chatList = mutableListOf()
        try {
            if (viewModel.conversation == null) {
                viewModel.initConversation()
            }

            viewModel.conversation?.apply {
                // 将所有消息标记为已读
                this.markAllMessagesAsRead()

                // 从数据库加载消息
                val dbMessages = this.loadMoreMsgFromDB(null, MAX_PAGESIZE)
                chatList.addAll(dbMessages)

                // 如果数据库中的消息数量等于 1，则从服务器获取更多消息
                if (dbMessages.size == 1) {
                    ChatClient.getInstance().chatManager().asyncFetchHistoryMessage(
                        viewModel.conversationId,
                        type,
                        MAX_PAGESIZE,
                        lastMessageId,
                        object : ValueCallBack<CursorResult<ChatMessage?>?> {
                            override fun onSuccess(value: CursorResult<ChatMessage?>?) {
                                value?.apply {
                                    lastMessageId = value.cursor

                                    // 检查从服务器获取的消息数量是否小于最大分页大小
                                    if (this.data.size < MAX_PAGESIZE) {
                                        mBinding.refresh.setEnableRefresh(false)
                                    }

                                    // 将服务器获取的消息添加到列表
                                    mBinding.rcvList.post {
                                        chatList.addAll(this.data.filterNotNull())
                                        chatAdapter.submitList(chatList)

                                        // 滚动到列表底部
                                        mBinding.rcvList.scrollToBottom()
                                    }

                                }
                            }

                            override fun onError(error: Int, errorMsg: String) {
                                Log.e("chat", "获取历史消息失败: $errorMsg")
                            }
                        })
                } else {
                    // 数据库中有足够的消息，直接使用这些消息
                    if (chatList.isNotEmpty()) {
                        lastMessageId = chatList[0].msgId
                    }

                    chatList.forEach {
                        Log.e("chat", "从数据库查到的msg: $it, msgid: ${it.msgId}, msgTime: ${it.msgTime}")
                    }

                    // 如果消息数量小于最大分页大小，则标记为漫游数据
                    if (chatList.size < MAX_PAGESIZE) {
                        loadDataType = LoadDataType.ROAM
                    }

                    chatAdapter.submitList(chatList)
                    mBinding.rcvList.scrollToBottom()
                }
            }
        } catch (e: Exception) {
            Log.e("chat", "获取聊天记录异常: ${e.message}")
            viewModel.conversation = null
        }
    }


    var chatList = mutableListOf<ChatMessage>()
    private fun initAdapter() {

        mBinding.rcvAlbum.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        mBinding.rcvAlbum.adapter =
            albumAdapter //   albumAdapter.addAll(listOf("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""))

        albumAdapter.setOnItemClickListener { _, _, index ->
            val userBuilder = Users.newBuilder()
            user?.let { it1 ->
                userBuilder.uid = it1.uid
                userBuilder.nickname = it1.nickname
                userBuilder.age = it1.age
                userBuilder.setCountryCode(it1.countryCode)
            }
            userBuilder.addAllMedia(items)

            LookBigImgActivity.openActivity(
                this@ChatActivity,
                userBuilder.build(),
                index,
                resultLauncher
            )


        }


        mBinding.rcvList.setVerticalLayoutManager()
        mBinding.rcvList.adapter = chatAdapter
        //  mBinding.rcvList.itemAnimator = DefaultItemAnimator()

        chatAdapter.animationEnable = true
        chatAdapter.addOnItemChildClickListener(R.id.rimHead) { _, view, position ->
            ARouterHelper.navigateToUserInfoActivity(this, viewModel.conversationId.toLong())
        }

        chatAdapter.addOnItemChildClickListener(R.id.imReport) { _, view, position ->
            try {
                val reportList = listOf(
                    SelectionItem(
                        getString(com.example.resources.R.string.report_1),
                        0,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_2),
                        1,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_3),
                        2,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_4),
                        3,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_5),
                        4,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_6),
                        5,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    ),
                    SelectionItem(
                        getString(com.example.resources.R.string.report_7),
                        6,
                        object :BottomSelectionListener{
                            override fun onTitleClicked(position: Int) {
                                viewModel.setReport(
                                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                                        .setReportContent((chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl)
                                        .build()
                                )
                            }

                        }
                    )
                )
                val reportDiaolg = BottomSelectionDialog.newInstance(reportList)
                reportDiaolg.show(this@ChatActivity.supportFragmentManager, "")
                reportDiaolg.setTitle(getString(com.example.resources.R.string.report))



            } catch (_: Exception) {
            }

        }
        chatAdapter.addOnItemChildClickListener(R.id.scvBtn) { _, view, position ->
            val userBuilder = Users.newBuilder()
            user?.let { it1 ->
                userBuilder.uid = it1.uid
                userBuilder.nickname = it1.nickname
                userBuilder.age = it1.age
                userBuilder.setCountryCode(it1.countryCode)
            }

            userBuilder.addAllMedia(items)
            viewModel.callsPhone(userBuilder.build())
        }

        chatAdapter.addOnItemChildClickListener(R.id.simImg) { _, view, position ->
            val intent = Intent(this, PhotoViewActivity::class.java)
            intent.putExtra(
                "url",
                (chatAdapter.getItem(position)?.body as ImageMessageBody).remoteUrl
            )
            val options =
                ActivityOptions.makeSceneTransitionAnimation(this, view, "thumbnailTransition")
            startActivity(intent, options.toBundle())
        }
        chatAdapter.addOnItemChildClickListener(R.id.imSendError) { _, view, position ->
            val dialog = CustomDialogFragment.newInstance(
                title = getString(com.example.resources.R.string.chat_msg_resend),
                content = "",
                positiveButtonText = getString(com.example.resources.R.string.yes),
                negativeButtonText = getString(com.example.resources.R.string.cancel),
                listener = object : CustomDialogFragment.DialogClickListener {
                    override fun onPositiveButtonClick() {
                        chatAdapter.getItem(position)?.let {
                            sendMseeage(it)
                        }

                    }

                    override fun onNegativeButtonClick() {
                    }
                })
            dialog.show(supportFragmentManager, "CustomDialog")
        }
        chatAdapter.addOnItemChildClickListener(R.id.imTranslate) { _, view, position ->
            com.weme.chat.ext.TranslationManager.addToQueue(
                position,
                (chatAdapter.getItem(position)?.body as TextMessageBody).message
            )
            user?.let {
                viewModel.setTranslate(
                    (chatAdapter.getItem(position)?.body as TextMessageBody).message,
                    getDeviceLanguage()
                )
            }


        }


        mBinding.edChat.setChatInputListener(this, viewModel.conversationId)
        mBinding.refresh.setEnableLoadMore(false)
        mBinding.refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) { //如果本地的消息是0
                viewModel.conversation?.apply {
                    if (loadDataType == LoadDataType.ROAM) {
                        Log.e("chat", "lastMessageId = "+lastMessageId)
                        ChatClient.getInstance().chatManager().asyncFetchHistoryMessages(
                            viewModel.conversationId,
                            type,
                            MAX_PAGESIZE,
                            lastMessageId,
                            FetchMessageOption(),
                            object : ValueCallBack<CursorResult<ChatMessage?>?> {
                                override fun onSuccess(value: CursorResult<ChatMessage?>?) {
                                    value?.apply {
                                        if (this.data.isEmpty()) {
                                            mBinding.refresh.finishRefresh()
                                            mBinding.refresh.setEnableRefresh(false)
                                            return
                                        }

                                        Log.e("chat", "Fetched ${this.data.size} messages")

                                        // 将 data 列表倒序
                                        val reversedData = this.data.reversed()


                                        if (lastMessageId == value.cursor) {
                                            mBinding.refresh.finishRefresh()
                                            return
                                        }
                                        lastMessageId = value.cursor
                                        Log.e("chat", "value.cursor = " + value.cursor)

                                        // 将倒序后的数据添加到 chatList 中
                                        chatList.addAll(0, reversedData.filterNotNull())

                                        mBinding.rcvList.post {
                                            chatAdapter.notifyItemRangeInserted(0, reversedData.size)
                                            mBinding.refresh.finishRefresh()
                                            mBinding.rcvList.scrollToBottom()
                                        }
                                    }
                                }


                                override fun onError(error: Int, errorMsg: String) {}
                            })

                    } else {
                        val newLastMsgList = loadMoreMsgFromDB(lastMessageId, MAX_PAGESIZE)

                        if (newLastMsgList.size == 1 && newLastMsgList[0].msgId == chatList[0].msgId) {
                            mBinding.refresh.finishRefresh()
                            mBinding.refresh.finishLoadMore()
                            return
                        }

                        chatList.addAll(0, newLastMsgList)
                        if(newLastMsgList.size>0){
                            lastMessageId = newLastMsgList[0].msgId
                        }

                        newLastMsgList?.forEach {
                            Log.e("chat", "     "+it!!.msgId)
                        }
                        if (newLastMsgList.size < MAX_PAGESIZE) {
                            loadDataType = LoadDataType.ROAM
                        }

                        mBinding.rcvList.post {
                            chatAdapter.notifyItemRangeInserted(0, newLastMsgList.size)
                            mBinding.refresh.finishRefresh()
                        }
                    }
                } ?: run {
                    mBinding.refresh.finishRefresh()
                    mBinding.refresh.finishLoadMore()
                }


            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {

            }

        })


    }




    private val albumAdapter = object : BaseQuickAdapter<Media, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Media?) {
            item?.apply {
                val smvImg = holder.getView<SmoothImageView>(R.id.smvImg)
                val imLock = holder.getView<ImageView>(R.id.imLock)
                val imPlay = holder.getView<ImageView>(R.id.imPlay)

                if (this.type.isTypeImg()) {
                    smvImg.loadImage(this.url)
                    imLock.gone()
                    imPlay.gone()
                } else {
                    if (isVip()) {
                        smvImg.loadImage(this.url)
                        imPlay.visible()
                        imLock.gone()
                    } else {
                        imPlay.gone()
                        Glide.with(this@ChatActivity).load(url).sizeMultiplier(0.5f)
                            .override(deviceSize.width, deviceSize.height / 2)
                            .error(com.example.resources.R.mipmap.icon_mine_pic_null).apply(
                            RequestOptions.placeholderOf(com.example.resources.R.drawable.icon_album_null)
                                .transform(GlideBlurTransformer(20, 2))
                        ).listener(object : RequestListener<Drawable> {
                            override fun onResourceReady(
                                resource: Drawable,
                                model: Any,
                                target: Target<Drawable>?,
                                dataSource: DataSource,
                                isFirstResource: Boolean
                            ): Boolean {
                                smvImg.fadeIn()
                                return false
                            }

                            override fun onLoadFailed(
                                e: GlideException?,
                                model: Any?,
                                target: Target<Drawable>,
                                isFirstResource: Boolean
                            ): Boolean {
                                return false
                            }
                        }).into(smvImg)
                        imLock.visible()
                    }
                }

            }

        }

        override fun onCreateViewHolder(
            context: Context,
            parent: ViewGroup,
            viewType: Int
        ): QuickViewHolder {
            return QuickViewHolder(R.layout.item_chat_album, parent)
        }


    }


    var msgListener = object : MessageListener {
        override fun onMessageReceived(messages: MutableList<ChatMessage>?) {
            viewModel.conversation?.apply {
                messages?.forEach {
                    if (it.conversationId() == viewModel.conversationId) when (it.type) {
                        ChatMessage.Type.TXT -> {
                            addMessage(it)
                        }

                        ChatMessage.Type.IMAGE -> {
                            it.setMessageStatusCallback(object : CallBack {
                                override fun onSuccess() {
                                    addMessage(it)
                                }

                                override fun onError(code: Int, error: String) { // 附件下载失败
                                }

                                override fun onProgress(progress: Int, status: String) { // 附件下载进度
                                }
                            }) // 下载附件

                            ChatClient.getInstance().chatManager().downloadAttachment(it)
                        }

                        ChatMessage.Type.CUSTOM -> {
                            addMessage(it)
                        }

                        else -> {

                        }
                    }
                }
                markAllMessagesAsRead() //未读清空
            } ?: run {
                onResume()
            }

        }

        override fun onCmdMessageReceived(messages: MutableList<ChatMessage>?) {
            super.onCmdMessageReceived(messages)
            for (msg in messages!!) {
                val body = msg.body as CmdMessageBody
                EMLog.i(
                    "chatactivity",
                    "Receive cmd message: " + body.action() + " - " + body.isDeliverOnlineOnly
                )
                runOnUiThread {
                    if (TextUtils.equals(msg.from, viewModel.conversationId)) {
                        if (TextUtils.equals(body.action(), AgoraClient.ACTION_TYPING_INPUT)) {
                            mBinding.tvTitle.text =
                                getString(com.example.resources.R.string.chat_typing)
                        } else if (TextUtils.equals(
                                body.action(),
                                AgoraClient.ACTION_TYPING_INPUT_END
                            )
                        ) {
                            mBinding.tvTitle.text = viewModel.userName
                        }
                    }
                }
            }
        }

    }


    override fun onTextEntered(text: String) {
        if (TextUtils.isEmpty(text)) return
        val message = ChatMessage.createTextSendMessage(text, viewModel.conversationId)
        message.chatType = ChatMessage.ChatType.Chat
        sendMseeage(message)
    }


    override fun finish() {
        alertDialog?.dismiss()
        super.finish()

    }

    override fun onImageEntered(text: String) {

        val message = ChatMessage.createImageSendMessage(text, false, viewModel.conversationId)
        sendMseeage(message)
    }

    fun getViewBinding(): ActivityChatBinding {
        return mBinding
    }

    fun getViewMode(): ChatViewMode {
        return viewModel
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.conversation?.apply {
            this.markAllMessagesAsRead()
        }
        mBinding.playerView.stopPlay()
        mBinding.playerView.release()
        mBinding.imCall.stopAnimation()
        mBinding.imCall.clear()
        ChatClient.getInstance().chatManager().removeMessageListener(msgListener)
        mBinding.edChat.removeChatInputListener()
        keyboardVisibilityListener.removeVisibilityListener(this)
    }

    var giftDialog: GiftDialog? = null

    override fun onShowGiftDialog() {
        if (null == giftDialog) {
            giftDialog = user?.let { GiftDialog(it.nickname, this) }
        }

        giftDialog?.show(this.supportFragmentManager, "")
    }

    override fun isMax2Msg(): Boolean {
        if (chatList.size < 2) {
            return false
        }
        return chatList.takeLast(2)
            .all { it.direct() == ChatMessage.Direct.SEND && it.type == ChatMessage.Type.TXT || it.type == ChatMessage.Type.IMAGE }

    }


    override fun onKeyboardVisibilityChanged(isVisible: Boolean, keyboardHeight: Int) {
        mBinding.edChat.setKeyboardVisibilityChanged(isVisible)
        // mBinding.rcvList.smoothScrollToBottom()
    }


    override fun onTitleClicked(position: Int) {
        when (position) {
            0 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_1))
                        .build()
                )
            }

            1 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_2))
                        .build()
                )
            }

            2 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_3))
                        .build()
                )
            }

            3 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_4))
                        .build()
                )
            }

            4 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_5))
                        .build()
                )
            }

            5 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_6))
                        .build()
                )
            }

            6 -> {
                viewModel.setReport(
                    ReportRequest.newBuilder().setReportUid(viewModel.conversationId.toLong())
                        .setReportContent(getString(com.example.resources.R.string.report_7))
                        .build()
                )
            }
        }
    }

    override fun sendGiftInfo(giftInfo: GiftInfo) {
        giftDialog?.dismiss()
        viewModel.sendGift(
            SendGiftRequest.newBuilder().setGiftId(giftInfo.id).setGiftNum(1)
                .setUid(viewModel.conversationId.toLong()).build()
        )

    }

    private val resultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
}